﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace Mvc_ImageUpload.Controllers
{
    public class DefaultController : Controller
    {
        //
        // GET: /Default/

        public ActionResult Index()
        {
            if (Request.Form.AllKeys.Count() == 0)
            {
                return View();
            }

            var msg = "请选择上传图片";

            var img = Request.Form["imgvalue"]; ;

            if (!string.IsNullOrWhiteSpace(img))
            {
                string[] filetype = { "gif", "png", "jpg", "jpeg", "bmp" };//文件允许格式	
                Regex reg = new Regex(@"(?<=\/)[^\/]+(?=\;)");
                string extName = reg.Match(img).ToString(); //文件扩展名

                if (!filetype.Contains(extName))    //"图片格式";
                {
                    msg = "图片格式错误";
                }
                else
                {
                    var path = string.Format("{0}/{1}/", "/upload", "images");  //上传服务器保存的路径			
                    var savePath = HttpContext.Server.MapPath(path);//保存到服务器上绝对路径

                    //保存的文件夹是否存在，不存在则创建
                    if (!Directory.Exists(savePath))
                    {
                        Directory.CreateDirectory(savePath);
                    }
                    var fileName = string.Format("{0}.{1}", DateTime.Now.Ticks.ToString(), extName);//保存的文件名
                    bool t = SaveImageFromBase64(img, savePath, fileName);
                    if (t)
                    {
                        ViewBag.Imgurl = path + fileName;//返回文件的相对路径，保存到数据库
                        msg = "保存成功";
                    }
                    else
                    {
                        msg = "保存失败";
                    }
                }
            }

            ViewBag.Msg = msg;
            return View();
        }

        /// <summary>
        /// 解码Base64字符串保存图片
        /// </summary>
        /// <param name="strBase64">base64</param>
        /// <param name="savePath">保存的路径</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static bool SaveImageFromBase64(string strBase64, string savePath, string fileName)
        {
            try
            {
                if (strBase64.Length > 0)
                {
                    int i = strBase64.IndexOf(',') + 1;
                    string base64 = strBase64.Substring(i, strBase64.Length - i);
                    byte[] b = Convert.FromBase64String(base64);
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(b);
                    System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                    img.Save(savePath + fileName);

                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
    }
}
